<?php

namespace app\backend\controller;

use app\backend\library\DataController;
use app\backend\validator\AddManagerValidator;
use app\backend\validator\ProfileValidator;
use app\backend\validator\UpdManagerValidator;
use app\common\model\AdminUser;
use think\Exception;
use think\exception\ValidateException;
use think\response\Json;

class Manager extends DataController
{
    protected $mdl = AdminUser::class;

    protected $allowMainFields = ['id', 'username', 'status', 'login_time', 'login_ip', 'last_time', 'created_at', 'updated_at', 'group_id'];

    protected $allowSortFields = [
        "id",
        "status",
        "created_at",
    ];

    protected $allowSearchFields = [
        'id',
        "username",
        'status',
        'login_ip',
        'created_at',
        'login_time',
    ];


    protected function applySearch($query, $params)
    {
        $curUserId = $this->request->user['user_id'];

        //将当前管理员账号排除
        if(!empty($params['id'])) {
            if($curUserId != $params['id']) {
                $query = $query->where('id', intval($params['id']));
            }
        }else{
            $query = $query->where('id','!=', $curUserId);
        }

        $query->where($this->mainFieldAlias('is_deleted'), $this->mdl::NO_DELETED)
            ->where($this->mainFieldAlias('group_id'), '>',0);

        parent::applySearch($query, $params);
    }

    protected function _saveBeforeHook(&$params)
    {
        if(empty($params['id'])) {
            $this->validate($params, AddManagerValidator::class);
        }else{
            $this->validate($params, UpdManagerValidator::class);
        }
    }

    /**
     * 获取个人信息
     * @return Json
     */
    public function profile()
    {
        $manager = $this->mdl::field($this->allowMainFields)
            ->where(['id' => $this->request->user['user_id']])
            ->find();

        return $this->jsonSuccess('success', $manager ?: []);
    }

    /**
     * 重置个人密码
     * @return Json
     */
    public function resetPassword()
    {
        try {
            $params = $this->request->param();

            $this->validate($params, ProfileValidator::class);

            $this->mdl::changeProfilePassword($params);

            //密码修改成功，强制用户重新登录
            return $this->forceUnauthorized('密码修改成功，请重新登录');

        } catch (ValidateException $e) {
            return $this->jsonError($e->getError());
        } catch (Exception $e) {
            return $this->jsonError($e->getMessage());
        }
    }
}